import random
import sqlite3
import time
from datetime import datetime, timedelta
from PIL import Image
import numpy as np

class DataSimulator:
    def __init__(self):
        self.conn = sqlite3.connect('sensor_data.db')
        self.running = False
        
    def simulate_sensor_data(self):
        # 生成随机温湿度数据
        temperature = round(20 + random.uniform(-5, 15), 1)
        humidity = round(30 + random.uniform(0, 70), 1)
        smoke = random.choice([0, 0, 0, 1])  # 25%概率触发烟雾报警
        
        # 存入数据库
        c = self.conn.cursor()
        c.execute("INSERT INTO sensor_data (temperature, humidity, smoke) VALUES (?, ?, ?)",
                 (temperature, humidity, smoke))
        self.conn.commit()
        
    def simulate_image_capture(self):
        # 生成随机测试图片
        img_array = np.random.randint(0, 255, (400, 400, 3), dtype=np.uint8)
        img = Image.fromarray(img_array)
        timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
        img_path = f"capture_{timestamp}.jpg"
        img.save(img_path)
        
        # 存入元数据库
        c = self.conn.cursor()
        c.execute("INSERT INTO image_metadata (image_path) VALUES (?)", (img_path,))
        self.conn.commit()
        
    def run_continuous_simulation(self):
        self.running = True
        try:
            while self.running:
                self.simulate_sensor_data()
                if random.random() < 0.3:
                    self.simulate_image_capture()
                time.sleep(5)
        except KeyboardInterrupt:
            print("\n安全停止模拟器...")
        finally:
            self.conn.close()

if __name__ == "__main__":
    simulator = DataSimulator()
    simulator.run_continuous_simulation()